/*
 *    Copyright 2010-2013 the original author or authors.
 *
 *    Licensed under the Apache License, Version 2.0 (the "License");
 *    you may not use this file except in compliance with the License.
 *    You may obtain a copy of the License at
 *
 *       http://www.apache.org/licenses/LICENSE-2.0
 *
 *    Unless required by applicable law or agreed to in writing, software
 *    distributed under the License is distributed on an "AS IS" BASIS,
 *    WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 *    See the License for the specific language governing permissions and
 *    limitations under the License.
 */
package com.google.code.jbauble.db.mysql;

import java.sql.Connection;
import java.sql.SQLException;
import java.util.List;

import javax.sql.DataSource;

import org.apache.commons.dbutils.DbUtils;
import org.apache.commons.dbutils.QueryRunner;
import org.apache.commons.dbutils.ResultSetHandler;
import org.apache.commons.dbutils.handlers.BeanHandler;
import org.apache.commons.dbutils.handlers.BeanListHandler;
import org.apache.commons.dbutils.handlers.ScalarHandler;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import com.google.code.jbauble.db.SqlNative;
import com.google.code.jbauble.db.SqlTransaction;
import com.google.code.jbauble.db.exception.DataAccessException;

public class MysqlNative implements SqlNative {
	protected DataSource datasource = null;
	
	public MysqlNative(DataSource ds) throws DataAccessException {
		try {
			datasource = ds;
		}
		catch (Exception e) {
			throw new DataAccessException(e);
		}
	}
	
	protected Logger log = LoggerFactory.getLogger(MysqlNative.class);
	
	/**
	 * 得到数据源，0读，1写
	 * @param type
	 * @return
	 * @throws SQLException 
	 */
	public Connection getConnection(int type) throws DataAccessException {
		try {
			return datasource.getConnection();
		} catch (SQLException e) {
			throw new DataAccessException(e);
		}
	}
	
	public <T> List<T> queryForList(String sql, Object[] objs, final Class<T> type) throws DataAccessException {
		Connection conn = null;
		try {
			conn = getConnection(0);
			return queryForList(conn, sql, objs, type);
		}
		finally {
			DbUtils.closeQuietly(conn);
		}
	}
	
	public <T> List<T> queryForList(Connection conn, String sql, Object[] objs, final Class<T> type) throws DataAccessException {
		try {
			QueryRunner runner = new QueryRunner();
			ResultSetHandler h = new BeanListHandler(type);
			return (List) runner.query(conn, sql, h, objs);
		} catch (SQLException e) {
			throw new DataAccessException(e);
		}
	}

	public <T> T queryForObject(String sql, Object[] objs, final Class<T> type) throws DataAccessException {
		Connection conn = null;
		try {
			conn = getConnection(0);
			QueryRunner runner = new QueryRunner();
			ResultSetHandler h = new BeanHandler(type);
			return queryForObject(conn, sql, objs, type);
		}
		finally {
			DbUtils.closeQuietly(conn);
		}
	}
	
	public <T> T queryForObject(Connection conn, String sql, Object[] objs, final Class<T> type) throws DataAccessException {
		try {
			QueryRunner runner = new QueryRunner();
			ResultSetHandler h = new BeanHandler(type);
			return (T)runner.query(conn, sql, h, objs);
		} catch (SQLException e) {
			throw new DataAccessException(e);
		}
	}
	
	public Long queryForLong(String sql, Object[] objs) throws DataAccessException {
		Connection conn = null;
		try {
			conn = getConnection(0);
			return queryForLong(conn, sql, objs); 
		}
		finally {
			DbUtils.closeQuietly(conn);
		}
	}
	
	public Long queryForLong(Connection conn, String sql, Object[] objs) throws DataAccessException {
		try {
			QueryRunner runner = new QueryRunner();
			return (Long)runner.query(conn, sql, new ScalarHandler(1), objs); 
		} catch (SQLException e) {
			throw new DataAccessException(e);
		}
	}
	
	public int execute(String sql, Object[] objs) throws DataAccessException {
		Connection conn = null;
		try {
			conn = getConnection(1);
			return execute(conn, sql, objs);
		}
		finally {
			DbUtils.closeQuietly(conn);
		}
	}
	
	public int execute(Connection conn, String sql, Object[] objs) throws DataAccessException {
		try {
			QueryRunner runner = new QueryRunner();
			return runner.update(conn, sql, objs);
		} catch (SQLException e) {
			throw new DataAccessException(e);
		}
	}
	
	public Object executeInsert(final String sql, final Object[] objs) throws DataAccessException {
		Connection conn = null;
		try {
			conn = getConnection(1);
			return executeInsert(conn, sql, objs); 
		}
		finally {
			DbUtils.closeQuietly(conn);
		}
	}
	
	public Object executeInsert(Connection conn, final String sql, final Object[] objs) throws DataAccessException {
		try {
			QueryRunner runner = new QueryRunner();
			runner.update(conn, sql, objs);
			return runner.query(conn, "SELECT LAST_INSERT_ID()", new ScalarHandler(1)); 
		} catch (SQLException e) {
			throw new DataAccessException(e);
		}
	}

	public SqlTransaction beginTransaction() throws DataAccessException {
		return new MysqlTransaction(this);
	}
}
